import React from 'react'
import { Menu } from 'antd'
import { RouterRawState, UserRawState } from '../../types'
import { ROUTER_LIST } from '../../router/routes'
import { useLocation, useNavigate } from 'react-router'


const generatorMenu = (routes: RouterRawState[], role: string) => {
  return routes.filter(v => {
    // 过滤显示隐藏  => hidden
    if (v.meta.hidden) return false
    return true
  }).filter(v => {
    // 过滤权限 => roles
    if(!v.meta.roles) return true;
    else return v.meta.roles.includes(role)
  
  }).sort((a, b) => {
    // 排序 => rank
    const rank1 = a.meta.rank === undefined ? 1: a.meta.rank
    const rank2 = b.meta.rank === undefined ? 1: b.meta.rank
    return rank1 - rank2
  }).map(v => {
    return {
      key: v.path,
      label: v.meta.label,
      icon: v.meta.icon
    }
  })

}

export const FVMenu: React.FC = () => {
  const datas = localStorage.getItem('userInfo')
  // 获取用户信息
  const userInfo: UserRawState = JSON.parse(datas ? datas : '{}')
  // 生成导航菜单
  const items = generatorMenu(ROUTER_LIST, userInfo.role)
  // 获取跳转hooks
  const navigate = useNavigate()
  // 获取访问路径
  const { pathname } = useLocation()
  
  return <Menu selectedKeys={[pathname]} items={items} theme="dark" onSelect={({ key }) => navigate(key)}></Menu>
}